package org.xtxg;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * 引导客户端
 */
public class HelloWorldClient {
    final String host;
    final int port;

    public HelloWorldClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new HelloWorldClient("localhost", 1314).start();
    }

    /**
     * 启动类
     */
    private void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ctx.writeAndFlush(Unpooled.copiedBuffer("你好，世界！", CharsetUtil.UTF_8));// 当被通知Channel是活跃的时候，发送一条消息
                                }

                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
                                    System.out.println("客户端收到：" + byteBuf.toString(CharsetUtil.UTF_8)); // 接收消息转储
                                    Thread.sleep(1000);
//                                    byteBuf.retain();
                                    channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(byteBuf));
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时，记录错误并关闭
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    });
            ChannelFuture future = bootstrap.connect().sync();// 连接到远程节点，阻塞等待直到连接完成
            future.channel().closeFuture().sync();// 阻塞，直到Channel关闭
        } finally {
            group.shutdownGracefully().sync();
        }
    }

}
